<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-08-03
 * @Time: 16:54
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： AliOSS.php
 */
namespace app\api\controller;

use app\common\model\ApiResponse;
use app\common\controller\Base;
use app\common\utils\OssUtil;
use think\Request;
use think\Validate;

class AliOSS extends Base {

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * gmt_iso8601
     * 生成ISO8601标准格式的时间
     *
     * @param $time
     * @return string
     */
    private function gmt_iso8601($time) {
        $dtStr = date("c", $time); //格式为2016-12-27T09:10:11+08:00
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601); //格式为2016-12-27T09:12:32+0800
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);//格式为2016-12-27T09:12:32
        return $expiration."Z";
    }

    /**
     * get_policy
     * 获取客户端直传文件的policy和签名
     * @api http://xxx/api/oss/get_policy
     *      dir 上传目录
     *      maxsize 最大允许文件大小，单位：MB
     *      expiretime 过期时间，单位：s（秒）
     *
     * @param Request $request
     * @return array
     */
    public function get_policy(Request $request)
    {
        $form = $request->post();

        // 表单验证
        $validate = new Validate([
            ['dir_type', 'require|^\\d+$', '上传目录类型不能为空|参数类型不正确'], // 上传目录类型
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

//        $dir_type = $form['dir_type'];
//        $dir = '';
//        switch ($dir_type) {
//            case 1:
//                $dir = 'images';
//                break;
//            case 2:
//                $dir = 'video';
//                break;
//        }
        $dir = 'users';

        // 最大允许文件大小
//        if (array_key_exists('maxsize', $form)) {
//            $maxSize = $form['maxsize'];
//        } else {
//            $maxSize = 256;
//        }

        // 过期时间
//        if (array_key_exists('expiretime', $form)) {
//            $expireTime = $form['expiretime'];
//        } else {
//            $expireTime = 30;
//        }

        // 计算过期时间
        $end = time() + 3000;
        // 生成ISO8601格式时间
        $expiration = $this->gmt_iso8601($end);

        $conditions = [];
        $conditions[] = array(0=>'content-length-range', 1=>0, 2=>1024*512); // 最大文件大小.用户可以自己设置 100M

        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir); //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $conditions[] = $start;

        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, config('aliYunOSS.AccessKeySecret'), true));

        $response = array();
        $response['accessid'] = config('aliYunOSS.AccessKeyId');
        $response['host'] = 'http://'.config('aliYunOSS.Bucket').'.'.config('aliYunOSS.EndPoint');
        $response['endpoint'] = config('aliYunOSS.EndPoint');
        $response['bucket'] = config('aliYunOSS.Bucket');
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['dir'] = $dir;  //这个参数是设置用户上传指定的前缀

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$response));
    }

    public function get_token() {

        $uid = checkUserToken(true);

        $form = $this->getAndCheckForm([
            ['content','require',],
        ]);
        $signature = trim(base64_encode(hash_hmac('sha1',
            $form['content'], config('aliYunOSS.AccessKeySecret', true))));

        return ApiResponse::success([
            'token' => 'OSS '.config('aliYunOSS.AccessKeyId').':'.$signature,
            'endpoint' => config('aliYunOSS.EndPoint'),
            'bucket' => config('aliYunOSS.Bucket'),
            'dir' => 'users/'.$uid,
        ]);
    }

    /**
     * base64ImgUpload
     * base64图形编码传到oss
     * @api http://xxx/api/oss/base64_upload
     *
     * @author zhengkai
     * @date 2017-12-01
     * @version 1.1
     *
     * @return \think\response\Json
     */
    public function base64ImgUpload()
    {
        $uid = checkUserToken(true);
        $base64 = input('post.file');

        preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result);
        $type = $result[2];    //获取图片的类型jpg png等
        $name = 'avatar_'.$uid.'.'.$type; //图片重命名

        $save_path = ROOT_PATH."public/upfile/";
        // 目录不存在则创建
        if(!file_exists($save_path)) mkdir($save_path,0777,true);

        file_put_contents($save_path.$name, base64_decode(str_replace($result[1], '', $base64)));

        $url = OssUtil::put('user/'.$name, $save_path.$name);

        if ($url) {
            unlink($save_path.$name);
            return json(array('code'=>200, 'msg'=>'上传成功！', 'data'=>$url));
        } else {
            return json(array('code'=>1012, 'msg'=>'上传失败！', 'data'=>null));
        }

    }
}